package com.dw.web.controller;

import cn.hutool.core.lang.UUID;
import com.dw.core.entity.Admin;
import com.dw.core.service.IAdminService;
import com.dw.web.dto.Response;
import com.dw.web.dto.input.LoginInputDto;
import com.dw.web.utils.RedisUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * @author zhangjing
 * @date 2020/8/21 15:48
 * @Description
 */
@RestController
@RequestMapping("/admin")
public class LoginController {

    @Autowired
    IAdminService adminService;

    @Autowired
    RedisUtils redisUtils;

    /**
     * 登陆
     * @param inputDto
     * @return
     */
    @PostMapping("/login")
    public Response login(@Validated @RequestBody LoginInputDto inputDto) {
        Admin admin = adminService.findByAdminName(inputDto.getUsername());
        if (admin == null) {
            return Response.error("账户不存在");
        }

        if (!StringUtils.equals(admin.getPassword(), inputDto.getPassword())) {
            return Response.error("密码不正确");
        }

        String token = UUID.fastUUID().toString();
        redisUtils.set("admin_login_token:" + token, admin);

        return Response.success(token);
    }

    /**
     *  有admin角色  perm_get_admin_info权限
     * @return
     */
    @RequiresPermissions(logical = Logical.OR, value = {"perm_get_admin_info"})
    @RequiresRoles(logical = Logical.OR, value = {"admin"})
    @GetMapping("/info")
    public Response getAdmin() {

        return Response.success();
    }

    /**
     * 需要测试接口权限
     * @return
     */
    @RequiresPermissions(logical = Logical.OR, value = {"perm_test_api"})
    @GetMapping("/perm/test")
    public Response testApi() {
        return Response.success();
    }


    /**
     * 不需要任何权限
     * @return
     */
    @GetMapping("/test1")
    public Response test1() {
        return Response.success();
    }

}
